package nl.infodation.emr.pricingservice.controller;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import com.vaadin.data.util.BeanItem;

import nl.infodation.emr.pricingservice.data.PublishedHistorySearchItem;
import nl.infodation.emr.pricingservice.entity.Environment;
import nl.infodation.emr.pricingservice.entity.PublishedHistory;
import nl.infodation.emr.pricingservice.ui.page.SessionData;
import nl.infodation.emr.utility.Constants;
import nl.infodation.emr.utility.StringUtil;

public class PublishedHistoryController extends AbstractBaseController<PublishedHistory, PublishedHistorySearchItem, Long> {

	@Override
	protected Boolean isObject(Field field) {
		if (field.getName().equals("environment")) {
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}

	@SuppressWarnings({ "rawtypes", "deprecation" })
	@Override
	public List<BeanItem> getPaginationByCriteria(PublishedHistorySearchItem object,
			int startPage, int pageSize) {
		
		final List<BeanItem> beans = new ArrayList<BeanItem>();
		EntityManager entityManager = null;
		try {
			entityManager = EM_FACTORY.createEntityManager();
			entityManager.getTransaction().begin();
				queryString.setLength(0);
				final PublishedHistorySearchItem item = object;
				
				// Process for role
				String roleName = SessionData.getRoleName();
				if (Constants.PROVEA_ROLE.equals(roleName)) {
					item.setBusLine(Constants.PROVEA_ROLE);
					
				} else if (Constants.AFM_ROLE.equals(roleName)) {
					item.setBusLine(Constants.AFM_ROLE);
				}
				
				final PublishedHistory p = new PublishedHistory();
				
				if (item.getDomainRuleID()>0) {
					p.setDomainRuleId(item.getDomainRuleID());
				}

				if (!StringUtil.isEmptyOrBlank(item.getRuleName())) {
					p.setRuleName(item.getRuleName());
				}
				if (!StringUtil.isEmptyOrBlank(item.getCountry())) {
					p.setCountry(item.getCountry());
				}
				if (!StringUtil.isEmptyOrBlank(item.getBusLine())) {
					p.setBusLine(item.getBusLine());
				}
				
				Environment envir = null;
				IController<Environment, Object, Integer> iController = ControllerFactory.getEnvironmentController();
				envir = iController.getObjectById(SessionData.getEnvironment());
				if (envir != null) {
					p.setEnvironment(envir);
					
					buildSelect(p);
					buildQueryAndParams(p);
					
					final TypedQuery<PublishedHistory> query = entityManager.createQuery(queryString.toString(), PublishedHistory.class);
					if (startPage > 0) {
						query.setFirstResult((startPage-1)*pageSize);
					} else {
						query.setFirstResult(1);
					}
					query.setMaxResults(pageSize);
					LOG.info("Executing the query \"{}\".", queryString);
					final List<PublishedHistory> results = query.getResultList();
					if(!results.isEmpty()) {
						for(PublishedHistory publishedHpistory : results) {
							beans.add(new BeanItem<PublishedHistory>(publishedHpistory));
						}
					}
				}
			entityManager.getTransaction().commit();
			
		} catch (IllegalStateException | IllegalAccessException ex) {
			LOG.error ("Error reading getPaginationByCriteria.", ex);
			if (entityManager != null && entityManager.getTransaction().isActive()) {
				LOG.info("Rolling back...");
				entityManager.getTransaction().rollback();
			}
		} finally {
			if (entityManager != null && entityManager.isOpen()) {
				entityManager.close();
			}
		}
		return beans;
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public long getTotalNumberItemByCriteria(PublishedHistorySearchItem object) {
		
		long number = 0;
		EntityManager entityManager = null;
		try {
			entityManager = EM_FACTORY.createEntityManager();
			entityManager.getTransaction().begin();
				queryString.setLength(0);
				final PublishedHistorySearchItem item = object;
				
				// Process for role
				String roleName = SessionData.getRoleName();
				if (Constants.PROVEA_ROLE.equals(roleName)) {
					item.setBusLine(Constants.PROVEA_ROLE);
					
				} else if (Constants.AFM_ROLE.equals(roleName)) {
					item.setBusLine(Constants.AFM_ROLE);
				}
				
				final PublishedHistory p = new PublishedHistory();
				
				if (item.getDomainRuleID()>0) {
					p.setDomainRuleId(item.getDomainRuleID());
				}

				if (!StringUtil.isEmptyOrBlank(item.getRuleName())) {
					p.setRuleName(item.getRuleName());
				}
				if (!StringUtil.isEmptyOrBlank(item.getCountry())) {
					p.setCountry(item.getCountry());
				}
				if (!StringUtil.isEmptyOrBlank(item.getBusLine())) {
					p.setBusLine(item.getBusLine());
				}
				
				Environment envir = null;
				IController<Environment, Object, Integer> iController = ControllerFactory.getEnvironmentController();
				envir = iController.getObjectById(SessionData.getEnvironment());
				if (envir != null) {
					p.setEnvironment(envir);
					
					buildSelectCount(p);
					buildQueryAndParams(p);
					
					final TypedQuery<Long> query = entityManager.createQuery(queryString.toString(), Long.class);
					LOG.info("Executing the query \"{}\".", queryString);
					number = query.getSingleResult();
				}
			entityManager.getTransaction().commit();
			
		} catch (IllegalStateException | IllegalAccessException ex) {
			LOG.error ("Error reading getPaginationByCriteria.", ex);
			if (entityManager != null && entityManager.getTransaction().isActive()) {
				LOG.info("Rolling back...");
				entityManager.getTransaction().rollback();
			}
		} finally {
			if (entityManager != null && entityManager.isOpen()) {
				entityManager.close();
			}
		}
		return number;
	}
	
	@Override
	protected PublishedHistory buildCriteria(PublishedHistorySearchItem search) {
		return new PublishedHistory();
	}

	
	
}
